package com.estun.backroundManagementService.modules.repory.service.impl;

import com.alibaba.excel.EasyExcelFactory;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.estun.backroundManagementService.modules.product.dto.ProductStatDTO;
import com.estun.backroundManagementService.modules.product.request.ProductRequest;
import com.estun.backroundManagementService.modules.product.service.ProductService;
import com.estun.backroundManagementService.modules.repory.model.ProductExcel;
import com.estun.backroundManagementService.modules.repory.model.WorkOrderExcel;
import com.estun.backroundManagementService.modules.repory.request.ProductDataRequest;
import com.estun.backroundManagementService.modules.repory.request.WorkOrderRequest;
import com.estun.backroundManagementService.modules.repory.service.ApiExcelService;
import com.estun.backroundManagementService.modules.workOrder.dto.WorkOrderEntity;
import com.estun.backroundManagementService.modules.workOrder.mapper.WorkOrderMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ApiExcelServiceImpl implements ApiExcelService {

    @Autowired
    private WorkOrderMapper workOrderMapper;

    @Autowired
    private ProductService productService;

    @Override
    public void exportExcelByCondition(HttpServletResponse response, WorkOrderRequest workOrderRequest) {
        try {
            QueryWrapper<WorkOrderEntity> queryWrapper = new QueryWrapper<>();
            if (StringUtils.isNotBlank(workOrderRequest.getBeginDate()) && StringUtils.isNotBlank(workOrderRequest.getEndDate())) {
                queryWrapper.between("schedule_start_time", workOrderRequest.getBeginDate(), workOrderRequest.getEndDate());
            }
            queryWrapper.orderByAsc("schedule_start_time");
            List<WorkOrderEntity> list = workOrderMapper.selectList(queryWrapper);
            if (list.size() > 10000) {
                throw new RuntimeException("数量过大，无法导出！");
            }
            List<WorkOrderExcel> orderExcels = list.stream().map(workOrderEntity -> {
                WorkOrderExcel orderExcel = new WorkOrderExcel();
                BeanUtils.copyProperties(workOrderEntity, orderExcel);
                orderExcel.setId(workOrderEntity.getId());
                orderExcel.setOrderCode(workOrderEntity.getOrderCode());
                orderExcel.setMaterialCode(workOrderEntity.getMaterialCode());
                orderExcel.setScheduleCode(workOrderEntity.getScheduleCode());
                orderExcel.setOrderQty(workOrderEntity.getOrderQty());
                orderExcel.setScheduleQty(workOrderEntity.getScheduleQty());
                orderExcel.setScheduleQtyFinished(workOrderEntity.getScheduleQtyFinished());
                orderExcel.setScheduleStartTime(workOrderEntity.getScheduleStartTime());
                String finishProgress = calculateCompletionPercentage(workOrderEntity.getScheduleQtyFinished(), workOrderEntity.getScheduleQty());
                orderExcel.setFinishProgress(finishProgress);

                return orderExcel;
            }).collect(Collectors.toList());
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition",
                    "attachment;filename=workOrder_excel_" + System.currentTimeMillis() + ".xlsx");

            EasyExcelFactory.write(response.getOutputStream(), WorkOrderExcel.class).sheet("工单生产").doWrite(orderExcels);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void exportExcelByCondition(HttpServletResponse response, ProductDataRequest productDataRequest) {
        try {
            ProductRequest productRequest = new ProductRequest();
            productRequest.getQuery().setCycle(productDataRequest.getCycle());
            productRequest.getQuery().setStationId(productDataRequest.getStationId());
            productRequest.getQuery().setBeginDate(productDataRequest.getBeginDate());
            productRequest.getQuery().setEndDate(productDataRequest.getEndDate());

            List<ProductStatDTO> list = productService.getProductStatByCycle(productRequest);
            if (list.size() > 10000) {
                throw new RuntimeException("数量过大，无法导出！");
            }
            List<ProductExcel> productExcelList = list.stream().map(productStatDTO -> {
                ProductExcel productExcel = new ProductExcel();
                BeanUtils.copyProperties(productStatDTO, productExcel);
                productExcel.setFinishProgress(productStatDTO.getQualifiedRate() + "%");
                return productExcel;
            }).collect(Collectors.toList());
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition",
                    "attachment;filename=product_data_excel_" + System.currentTimeMillis() + ".xlsx");

            EasyExcelFactory.write(response.getOutputStream(), ProductExcel.class).sheet("产能统计").doWrite(productExcelList);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String calculateCompletionPercentage(int completed, int total) {
        if (total < 0) {
            throw new IllegalArgumentException("总任务数不能为负数");
        }
        if (total == 0) {
            return "0.00%";
        }
        double completionRate = ((double) completed / total) * 100;
        DecimalFormat df = new DecimalFormat("0.00");
        return df.format(completionRate) + "%";
    }


}
